package common;


import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoDestinationManager;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.ext.DestinationDataProvider;
import config.SAPConnConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Properties;

/**
 * 与SAP连接配置
 *
 * @author jay
 */
public final class SAPConnUtil {
    private static final String ABAP_AS_POOLED = "ABAP_AS_WITH_POOL";

    private static Logger logger = LoggerFactory.getLogger(SAPConnUtil.class);

    static {
        SAPConnConfig sapConnConfig = SpringContextUtil.getBean(SAPConnConfig.class);

        Properties connectProperties = new Properties();
        //105系统 测试
        String sss = sapConnConfig.getAshost();
        connectProperties.setProperty("jco.client.ashost", sapConnConfig.getAshost());
        connectProperties.setProperty("jco.client.sysnr", sapConnConfig.getSysnr());
        connectProperties.setProperty("jco.client.client", sapConnConfig.getClient());
        connectProperties.setProperty("jco.client.user", sapConnConfig.getUser());
        connectProperties.setProperty("jco.client.passwd", sapConnConfig.getPasswd());
        connectProperties.setProperty("jco.client.lang", sapConnConfig.getLang());

        //JCo连接到SAP服务器有两种方法，分别是直连和通过连接池进行连接。其差别在于，打开直连连接后可以一直保持连接；连接池则是在需要时才建立连接，连接暂不需要时，将被释放回连接池，再分配给其他用户使用。在网络服务器应用程序里，一般采用连接池进行连接SAP服务器。
        connectProperties.setProperty(DestinationDataProvider.JCO_POOL_CAPACITY, "3");  //最大连接数
        connectProperties.setProperty(DestinationDataProvider.JCO_PEAK_LIMIT, "10");     //最大连接线程
        createDataFile(ABAP_AS_POOLED, "jcoDestination", connectProperties);
    }

    /**
     * 创建SAP接口属性文件。
     *
     * @param name       ABAP管道名称
     * @param suffix     属性文件后缀
     * @param properties 属性文件内容
     */
    private static void createDataFile(String name, String suffix, Properties properties) {
        File cfg = new File(name + "." + suffix);
        if (cfg.exists()) {
            cfg.deleteOnExit();
        }
        try {
            FileOutputStream fos = new FileOutputStream(cfg, false);
            properties.store(fos, "for tests only !");
            fos.close();
        } catch (Exception e) {
            logger.error("Create Data file fault, error msg: " + e.toString());
            throw new RuntimeException("Unable to create the destination file " + cfg.getName(), e);
        }
    }

    /**
     * 获取SAP连接
     *
     * @return SAP连接对象
     */
    public static JCoDestination connect() {
        JCoDestination destination = null;
        try {
            destination = JCoDestinationManager.getDestination(ABAP_AS_POOLED);
        } catch (JCoException e) {
            logger.error("Connect SAP fault, error msg: " + e.toString());
            throw new RuntimeException("Unable to create the destination file ", e);
        }
        return destination;
    }
}